/*
 * @Date: 2023-01-06 08:57:08
 * @LastEditors: 许成志 18296777223@163.com
 * @LastEditTime: 2023-01-17 18:05:59
 */
/**
 * @description: 扁平化结构转树形结构
 * @param {Array} arrayList 扁平化结构数组
 * @param {String} idStr
 * @param {String} pidStr
 * @param {String} childrenStr
 * @return {Array}
 */
export function flatToTree({arrayList, idStr = 'id', pidStr = 'pid', childrenStr = 'children'}){
    // 存储arrayList转换成{key: value}
    let arrayObjs = {}
    // 存储最终树形结构数据
    let treeList = []
    // 将arrayList转换成{key: value}结构
    arrayList.forEach(item => {
        arrayObjs[item[idStr]] = item
    });
    console.log("扁平化arrayList=", arrayList)
    // 根据pid来将数据转换成树形结构
    arrayList.forEach(item => {
      // 判断父级是否存在 
      let parentId = item[pidStr]
      if(parentId) {
        // 如果有没有父级children字段，就创建一个children字段
        !arrayObjs[parentId][childrenStr] && (arrayObjs[parentId][childrenStr] = [])
        arrayObjs[parentId][childrenStr].push(item)
      } else {
        treeList.push(item)
      }
    });
    console.log("树形结构treeList=", treeList)
    return treeList
}